package com.lakeworks.decision.base;

import com.alibaba.fastjson.JSONObject;
import com.lakeworks.common.domain.ticket.TktDecision;
import com.lakeworks.common.domain.ticket.TktTicket;
import com.lakeworks.common.enums.ticket.FlowType;
import com.lakeworks.common.enums.ticket.TicketStatus;
import com.lakeworks.domain.OprPickup;
import com.lakeworks.mapper.OprPickupMapper;
import com.lakeworks.mapper.OprProductMapper;
import com.lakeworks.mapper.TktTicketMapper;
import com.lakeworks.service.api.DetectMethodAnnotation;
import com.lakeworks.service.api.MerchantApiService;
import com.lakeworks.service.api.MerchantAsync;
import com.lakeworks.service.impl.TktTicketServiceImpl;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Getter
public class BaseDecisionHandler {

    @Autowired
    private TktTicketMapper tktTicketMapper;


    @Autowired
    private MerchantAsync merchantAsync;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private OprPickupMapper oprPickupMapper;

    @Autowired
    private DetectMethodAnnotation detectMethodAnnotation;

    private static final Logger log = LoggerFactory.getLogger(BaseDecisionHandler.class);


    public void updateTicketState(TktTicket tktTicket) {
        tktTicketMapper.updateTktTicket(tktTicket);
    }

    public TktDecision getTktDecision(TktTicket tktTicket, Decision decision) {
        TktDecision build = TktDecision.builder().build();
        if (tktTicket != null) {
            build.setCreateBy(tktTicket.getCreateBy());
            build.setModifyBy(tktTicket.getModifyBy());
            build.setTicketId(tktTicket.getId());
            build.setType(decision.getType().name());
            build.setDetail(JSONObject.toJSONString(decision));
        }
        return build;
    }

    public Logger getLog(){return log;}

    public Long getChannelId(String orderNo){
        List<OprPickup> pickups = oprPickupMapper.selectPickupList(OprPickup.builder().orderNo(orderNo).build());
        if(!CollectionUtils.isEmpty(pickups)){
           return pickups.get(0).getChannelId();
        }
        return null;
    }

    public void closeRelevanceTicket(TktTicket tktTicket){
        if(tktTicket.getRelevanceId() != null && !tktTicket.getType().equals(FlowType.LOSE_LESS.name())){
            TktTicket ticket = tktTicketMapper.selectTktTicketById(tktTicket.getRelevanceId());
            if(ticket != null){
                TktTicket build = TktTicket.builder().build();
                build.setId(ticket.getId());
                build.setStatus(TicketStatus.FINISHED.name());
                updateTicketState(build);
                closeRelevanceTicket(ticket);
            }
        }
    }


}
